<template>
  <div>
    <input type="text" v-model="data.link" placeholder="链接地址" /><br/>
    <input type="text" v-model="data.alt" placeholder="提示信息" /><br/>
    <input type="file" ref="fileRef" @change="previewImage"/><br/>
    <input type="text" hidden v-model="data.img" placeholder="图片地址" /><br/>
    <img ref="imgRef" src="" alt="" /><br/>
    <button @click="uploadBanner">上传</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue'
import { addBannerItem } from '../../api/banner'
import { useRouter } from 'vue-router'
export default defineComponent({
  setup () {
    const fileRef = ref()
    const imgRef = ref()

    const data = reactive({
      link: '',
      alt: '',
      img: ''
    })
    const previewImage = () => {
      console.log(fileRef)
      const file = fileRef.value.files[0]
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = function () {
        imgRef.value.src = this.result
        data.img = imgRef.value.src
      }
    }

    const router = useRouter()
    const uploadBanner = () => {
      addBannerItem(data).then(() => {
        router.push('/banner/list')
      })
    }
    return {
      fileRef,
      imgRef,
      previewImage,
      data,
      uploadBanner
    }
  }
})
</script>

<style lang="" scoped>

</style>
